package com.xinxing.city.recovery.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.xinxing.city.recovery.BR;
import com.xinxing.city.recovery.Constant;
import com.xinxing.city.recovery.DI;
import com.xinxing.city.recovery.DeviceKernel;
import com.xinxing.city.recovery.R;
import com.xinxing.city.recovery.Tools;
import com.xinxing.city.recovery.adapter.AreaSelAdapter;
import com.xinxing.city.recovery.adapter.CompanyAdapter;
import com.xinxing.city.recovery.entitys.AreaSelBean;
import com.xinxing.city.recovery.entitys.BucketType;
import com.xinxing.city.recovery.entitys.Cabinet;
import com.xinxing.city.recovery.entitys.Catalogs;
import com.xinxing.city.recovery.entitys.CityDistrict;
import com.xinxing.city.recovery.entitys.Company;
import com.xinxing.city.recovery.entitys.HardwareCategory;
import com.xinxing.city.recovery.entitys.HeatBucket;
import com.xinxing.city.recovery.entitys.LocalBean;
import com.xinxing.city.recovery.entitys.OwnerInfo;
import com.xinxing.city.recovery.interfaces.IDeviceKernel;
import com.xinxing.city.recovery.interfaces.OnItemClickListener;
import com.xinxing.city.recovery.net.BaseTask;
import com.xinxing.city.recovery.net.OkHttpRequest;
import com.xinxing.city.recovery.net.RetroFactory;
import com.xinxing.city.recovery.utils.MyDialog;
import com.xinxing.city.recovery.utils.SharedPreferencesUtils;
import com.xinxing.city.recovery.utils.WebViewJs;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SetCabinetActivity extends AppCompatActivity {
    private LocalBean local;
    WebView webView;
    private CompanyAdapter companyAdapter;
    private TextView tvSelect;
    private List<Company> companyList = new ArrayList<>();
    private  ProgressBar progressBar;
    private List<HardwareCategory> hardType;
    private OwnerInfo owner;
    private List<AreaSelBean> areaList;
    private List<AreaSelBean> villageList;
    private Cabinet infodata = null;
    private Integer villageSel;
    private Gson gson;
    private IDeviceKernel deviceKernel;
    private boolean t = false;
    private  List<Catalogs> catalogsList;
    private List<BucketType> bucketTypes =new ArrayList<>();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        hookWebView();
        setContentView(R.layout.activity_set_cabinet);
        local = new LocalBean();
        deviceKernel = DI.getInstance(IDeviceKernel.class);
        progressBar = findViewById(R.id.progressBar);
        webView = findViewById(R.id.mapViewCon);
        webView.loadUrl("http://map.maidmao.com/smap.html");
        String code = getIntent().getStringExtra("code");
        WebSettings webSettings = webView.getSettings();
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setGeolocationEnabled(true);
        gson = new Gson();
        // 添加JavaScript接口
        WebViewJs webViewInterface = new WebViewJs(this,getSupportFragmentManager());
        webView.addJavascriptInterface(webViewInterface, "AndroidInterface");
        String str = (String) SharedPreferencesUtils.getParam(this,"set_category","");

        if (!str.equals("")) {
            Type dev = new TypeToken<List<Catalogs>>() {}.getType();
            catalogsList = gson.fromJson(str, dev);
        }else{
            catalogsList = new ArrayList<>();
        }
        if (code.equals("")) webViewInterface.ipPos(webView);
        initPage();
    }
    private void initPage() {
        tvSelect = findViewById(R.id.tv_select);
        String c_c = (String) SharedPreferencesUtils.getParam(this,"cabinet","");
        if (!c_c.equals("")) {
            Type cType = new TypeToken<Cabinet>() {}.getType();
            infodata = gson.fromJson(c_c,cType);

            local.setLat(Double.parseDouble(infodata.getLatitude()));
            local.setLng(Double.parseDouble(infodata.getLongitude()));
            local.setAddress(infodata.getAddress());

            mapPostion(local.getLat(),local.getLng());

            webView.loadUrl("http://map.maidmao.com/smap.html?lat="+local.getLat()+"&lng="+local.getLng());

            if (infodata.getStatus().equals("00")) {
                // 根据id找到选中的RadioButton
                RadioButton btn1 = findViewById(R.id.cabinet_status_btn1);
                btn1.setChecked(true);
            }  else {
                RadioButton btn2 = findViewById(R.id.cabinet_status_btn2);
                btn2.setChecked(true);
            }

            if (infodata.getTradingStatus()!=null&&infodata.getTradingStatus().equals("00")) {
                // 根据id找到选中的RadioButton
                RadioButton btn1 = findViewById(R.id.cabinet_tradingStatus_btn1);
                btn1.setChecked(true);
            }  else {
                RadioButton btn2 = findViewById(R.id.cabinet_tradingStatus_btn2);
                btn2.setChecked(true);
            }

            EditText ename = findViewById(R.id.cabinet_name);
            ename.setText(infodata.getName());

            EditText emodel = findViewById(R.id.cabinet_equipmentModel);
            emodel.setText(infodata.getEquipmentModel());

            EditText efacturer = findViewById(R.id.cabinet_manufacturer);
            efacturer.setText(infodata.getManufacturer());

            if(infodata.getCompanyName()!=null)
                tvSelect.setText(infodata.getCompanyName());

        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},0x123);
        }
    }
    @SuppressLint("MissingPermission")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0x123 && grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //创建locationManger对象
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            //获取最新的定位信息
            Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            updateView(lastKnownLocation);
            //每隔三秒获取一次GPS信息
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 8f, new LocationListener() {
                @Override
                public void onLocationChanged(@NonNull Location location) {
                    updateView(location);
                }
            });
        }
    }
    private void updateView(Location location) {
        if (location != null) {
            String res = "实时位置：\n" +
                    "经度：" + location.getLongitude() +
                    "\n纬度：" + location.getLatitude() +
                    "\n高度：" + location.getAltitude() +
                    "\n速度：" + location.getSpeed()
                    + "\n方向：" + location.getBearing();
            Log.d("TAG", "updateView: "+res);

        }else{
            Log.d("TAG", "updateView: 111");
        }
    }

            //位置更新
    public void mapLatlngChange(Double lat,Double lng) {
        local.setLat(lat);
        local.setLng(lng);
        String ll = Tools.convertGCJ2WGS(lng,lat);
        Log.e("e",lat+","+lng+"||"+ll);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mapPostion(local.getLat(),local.getLng());
            }
        });
    }
    private int position;
    /**
     * 回收柜登记展开
     */
    public void cabinetShow(View view) {

//        try {
            if (local.getLat() <= 0 || local.getLng() <= 0 || local.getAddress().equals("")) {
                MyDialog myDialog = MyDialog.newInstance("提示","定位失败,请重新定位！","确定","");
                myDialog.setMyDialogListener(new MyDialog.MyDialogListener() {
                    @Override
                    public void onPositiveClick() {
                        myDialog.dismiss();
                    }
                    @Override
                    public void onNegativeClick() {

                    }
                });
                myDialog.show(getSupportFragmentManager(),"MyDialog");
                return ;
            }

            //加载页面
            RelativeLayout cabinetReg = findViewById(R.id.regCabinet);
            cabinetReg.setVisibility(View.VISIBLE);
            RecyclerView lv= findViewById(R.id.lv_company);
            RelativeLayout rlySelectCompany = findViewById(R.id.rly_select_company);
            LinearLayout llySelectCompany = findViewById(R.id.lly_select_company);
            companyAdapter = new CompanyAdapter(R.layout.adapter_company, BR.company);


            lv.setLayoutManager(new LinearLayoutManager(this,RecyclerView.VERTICAL,false));
            lv.setAdapter(companyAdapter);
            rlySelectCompany.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(!t) {
                        llySelectCompany.setVisibility(View.VISIBLE);
                        t = true;
                    }
                    else{
                        llySelectCompany.setVisibility(View.GONE);
                        t=false;
                    }
                }
            });
            companyAdapter.setOnItemClickListener((view1, p) -> {
                tvSelect.setText(companyList.get(p).getFullName());
                llySelectCompany.setVisibility(View.GONE);
                position = p;
            });

            //加载物权人信息
            getOwnerInfo();
            getCompany();
            //加载分类信息
            getHardType();

//        } catch (Exception e) {
//            Tools.logTips("错误信息:"+e.getMessage(),getSupportFragmentManager());
//        }

    }
    public void getCompany(){
        ProgressBar progressBar = findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE); // 显示加载动画
        String city="";
        if(villageList!=null &&villageList.get(villageSel)!=null){
            city = villageList.get(villageSel).getCityName();
        }
//        String city = "北京";
        new BaseTask<List<Company>>(this, RetroFactory.getJsonService().getCompany(city)).handleResponse(new BaseTask.ResponseListener<List<Company>>() {


            @Override
            public void onSuccess(List<Company> companies) {
                hideLoadding(progressBar);
                Log.e("TTT","dd "+companies.size());
                companyList= companies;
                companyAdapter.setmDatas(companies);

            }

            @Override
            public void onFail() {
                hideLoadding(progressBar);
            }
        });


    }
    /**
     * 回收柜登记提交
     */
    public void cabinetSub(View view){
        Cabinet cabinet = new Cabinet();
        Map<String,String> par = new HashMap<>();

        HardwareCategory itype =  hardType.get(0);
        par.put("equipmentName", itype.getName());
        cabinet.setEquipmentName(itype.getName());
        par.put("hardwareCode", itype.getCode());
        cabinet.setHardwareCode(itype.getCode());
        if(companyList.size()>position) {
            par.put("companyCode", companyList.get(position).getCode());
            cabinet.setCompanyCode(companyList.get(position).getCode());
            par.put("companyName", companyList.get(position).getFullName());
            cabinet.setCompanyName(companyList.get(position).getFullName());
        }
        RadioGroup radioGroup = findViewById(R.id.cabinet_status);
        // 获取选中的RadioButton的id
        int selectedRadioButtonId = radioGroup.getCheckedRadioButtonId();
        String state1 = "00";
        if (selectedRadioButtonId != -1) {
            // 根据id找到选中的RadioButton
            RadioButton selectedRadioButton = findViewById(selectedRadioButtonId);
            // 获取选中的RadioButton的值
            String selectedValue = selectedRadioButton.getText().toString();

            if (!selectedValue.equals("开启")) {
                state1 = "01";
            }
        }
        par.put("status", state1);
        cabinet.setStatus(state1);
        RadioGroup radioGroup2 = findViewById(R.id.cabinet_tradingStatus);
        // 获取选中的RadioButton的id
        int selectedRadioButtonId2 = radioGroup2.getCheckedRadioButtonId();
        String state2 = "00";
        if (selectedRadioButtonId2 != -1) {
            // 根据id找到选中的RadioButton
            RadioButton selectedRadioButton = findViewById(selectedRadioButtonId2);
            // 获取选中的RadioButton的值
            String selectedValue = selectedRadioButton.getText().toString();
            if (!selectedValue.equals("空闲")) {
                state2 = "01";
            }
        }
        par.put("tradingStatus", state2);
        cabinet.setTradingStatus(state2);
        par.put("cityDistrict", villageList.get(villageSel).getCityDistrict());
        cabinet.setCityDistrict(villageList.get(villageSel).getCityDistrict());
        par.put("cityCode", villageList.get(villageSel).getCityCode());
        cabinet.setCityCode(villageList.get(villageSel).getCityCode());
        par.put("cityName", villageList.get(villageSel).getCityName());
        cabinet.setCityName( villageList.get(villageSel).getCityName());
        par.put("countyDistrict", villageList.get(villageSel).getCountyDistrict());
        cabinet.setCountyDistrict(villageList.get(villageSel).getCountyDistrict());
        par.put("countyCode", villageList.get(villageSel).getCountyCode());
        cabinet.setCountyCode(villageList.get(villageSel).getCountyCode());
        par.put("countyName", villageList.get(villageSel).getCountyName());
        cabinet.setCountyName(villageList.get(villageSel).getCountyName());
        par.put("zoneCode", villageList.get(villageSel).getCode());
        cabinet.setZoneCode(villageList.get(villageSel).getCode());
        par.put("zoneName", villageList.get(villageSel).getName());
        cabinet.setZoneName(villageList.get(villageSel).getName());
        par.put("address", local.getAddress());
        cabinet.setAddress(local.getAddress());
        String ll = Tools.convertGCJ2WGS(local.getLng(),local.getLat());
        String[] laln = ll.split(",");
        par.put("longitude", laln[0]);
        cabinet.setLongitude(laln[0]);
        cabinet.setLatitude(laln[1]);
        par.put("latitude", laln[1]);

        par.put("realRightOwner", owner.getRealRightOwner());
        cabinet.setRealRightOwner(owner.getRealRightOwner());
        par.put("realRightOwnerID", owner.getRealRightOwnerID());
        cabinet.setRealRightOwnerID(owner.getRealRightOwnerID());
        par.put("realRightOwnerName", owner.getRealRightOwnerName());
        cabinet.setRealRightOwnerName(owner.getRealRightOwnerName());
        EditText ename = findViewById(R.id.cabinet_name);
        par.put("name", ename.getText().toString());
        cabinet.setName( ename.getText().toString());
        EditText emodel = findViewById(R.id.cabinet_equipmentModel);
        par.put("equipmentModel", emodel.getText().toString());
        cabinet.setEquipmentModel( emodel.getText().toString());
        EditText efacturer = findViewById(R.id.cabinet_manufacturer);
        par.put("manufacturer", efacturer.getText().toString());
        cabinet.setManufacturer( efacturer.getText().toString());

        par.put("deviceSerialNum", DeviceKernel.deviceSerialNum);
        cabinet.setDeviceSerialNum(DeviceKernel.deviceSerialNum);
        setCabinetAdd( cabinet,par);
    }

    /**
     * 注册柜信息
     */
    private void setCabinetAdd(Cabinet cabinet,Map<String, String> par) {

        progressBar.setVisibility(View.VISIBLE); // 显示加载动画

        OkHttpRequest httpRequest = new OkHttpRequest(this,getSupportFragmentManager());


        String url = "/sr-recycling/v1/pub/recycling_cabinet/add";
        if (infodata != null ) {
            par.put("code",infodata.getCode());

            url = "/sr-recycling/v1/pub/recycling_cabinet/update";
        }
        Log.e("柜子添加",gson.toJson(par));
        String finalUrl = url;
        httpRequest.sendPostRequest(url,gson.toJson(par), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                hideLoadding(progressBar);
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                hideLoadding(progressBar);
                JsonObject jsonObject = httpRequest.getResData();
                Log.e("柜子添加",finalUrl+"||"+gson.toJson(jsonObject));
                if (jsonObject == null) {return ;}

                if (finalUrl == "/sr-recycling/v1/pub/recycling_cabinet/add") {
                    //永久保存

                    cabinet.setCode(jsonObject.get("data").getAsString());
                } else {

                    cabinet.setCode(infodata.getCode());
                }
                deviceKernel.getRuntime().setCabinet(cabinet);
                SharedPreferencesUtils.setParam(SetCabinetActivity.this,"cabinet",gson.toJson(cabinet));
                if(Constant.screenWidth ==800){
                    bucketSub("全品类",cabinet,0);
                }else{
                    bucketSub("纸类",cabinet,1);

                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        deviceKernel.initConfig();
                        MyDialog myDialog = MyDialog.newInstance("提示","设置成功！返回设备管理！","确定","取消");
                        myDialog.setMyDialogListener(new MyDialog.MyDialogListener() {
                            @Override
                            public void onPositiveClick() {
//                                SharedPreferencesUtils.clear(SetCabinetActivity.this);
                                deviceKernel.initConfig();
                                finish();
                            }
                            @Override
                            public void onNegativeClick() {
                                myDialog.dismiss();
//                                SharedPreferencesUtils.clear(SetCabinetActivity.this);
                                deviceKernel.initConfig();
                                sendHeat();

                            }
                        });
                        myDialog.show(getSupportFragmentManager(),"MyDialog");
                    }
                });

                response.close();
            }
        });
    }

    /**
     * 加载分类信息
     */
    private void getHardType() {

        progressBar.setVisibility(View.VISIBLE); // 显示加载动画
        new BaseTask<List<HardwareCategory>>(this, RetroFactory.getJsonService().getHardware()).handleResponse(new BaseTask.ResponseListener<List<HardwareCategory>>() {
            @Override
            public void onSuccess(List<HardwareCategory> hardwareCategories) {
                hideLoadding(progressBar);
                hardType = hardwareCategories;
            }

            @Override
            public void onFail() {
                hideLoadding(progressBar);
            }
        });
    }

    /**
     * 获取物权信息
     */
    private void getOwnerInfo() {

        progressBar.setVisibility(View.VISIBLE); // 显示加载动画
        new BaseTask<OwnerInfo>(this,RetroFactory.getJsonService().getOwnerInfo()).handleResponse(new BaseTask.ResponseListener<OwnerInfo>() {


            @Override
            public void onSuccess(OwnerInfo ownerInfo) {
                hideLoadding(progressBar);
                owner = ownerInfo;
            }

            @Override
            public void onFail() {
                hideLoadding(progressBar);
            }
        });

    }

    /**
     * 获取相关位置信息
     */
    public void mapPostion(double lat,double lng) {

        progressBar.setVisibility(View.VISIBLE); // 显示加载动画


        //根据经纬度获取位置信息
        OkHttpRequest httpRequest = new OkHttpRequest(this,getSupportFragmentManager());
        httpRequest.mapSendGetRequest("/ws/geocoder/v1/?location="+lat+","+lng+"&key=D3XBZ-ETZWP-BCBDT-LBX7J-DNGZK-5BBVD&get_poi=1", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                hideLoadding(progressBar);
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                hideLoadding(progressBar);

                JsonObject jsonObject = httpRequest.getResData();
                if (jsonObject == null) {return ;}

                JsonObject resData = jsonObject.get("result").getAsJsonObject();
                JsonObject resAd = resData.get("ad_info").getAsJsonObject();

                local.setAddress(resData.get("address").getAsString());
                local.setCityBm(resAd.get("adcode").getAsString().substring(0,4)+"00");
                local.setCityCode(resAd.get("city_code").getAsString());
                local.setCityName(resAd.get("city").getAsString());

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        EditText address = findViewById(R.id.temp_address);
                        address.setText(local.getAddress());

                        EditText latlng = findViewById(R.id.temp_latlng);
                        latlng.setText(local.getLat()+","+local.getLng());

                        EditText city = findViewById(R.id.temp_city);
                        city.setText(local.getCityName());
                        //请求行政区接口
                        getArea();
                    }
                });
                response.close();
            }
        });
    }

    /**
     * 请求行政区接口
     */
    private void getArea() {
        new BaseTask<List<CityDistrict>>(this,RetroFactory.getJsonService().getCityDistrict(local.getCityBm())).handleResponse(new BaseTask.ResponseListener<List<CityDistrict>>() {

            @Override
            public void onSuccess(List<CityDistrict> cityDistricts) {
                areaList = new ArrayList<>();
                Integer selP = 0;
                for(int i=0;i<cityDistricts.size();i++){
                    CityDistrict item = cityDistricts.get(i);
                    AreaSelBean sel = new AreaSelBean();
                    sel.setCityCode(item.getCityCode());
                    sel.setCityName(item.getCityName());
                    sel.setCityDistrict(item.getCityDistrict());
                    sel.setCode(item.getDistrictCode());
                    sel.setName(item.getDistrictName());
                    if (infodata != null && infodata.getCountyDistrict().equals(sel.getCode())) {
                        selP = i;

                    }
                    areaList.add(sel);
                }

                Integer finalSelP = selP;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        Spinner spinner = findViewById(R.id.temp_area);
                        AreaSelAdapter adapter = new AreaSelAdapter(SetCabinetActivity.this, android.R.layout.simple_spinner_item, areaList);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinner.setAdapter(adapter);

                        spinner.setSelection(finalSelP);

                        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                // 当选择项改变时触发的操作
                                getVillage(position);
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {
                                // 当未选择任何项时触发的操作
                            }
                        });

                    }
                });

            }

            @Override
            public void onFail() {

            }
        });

    }

    /**
     * 请求小区接口
     */
    private void getVillage(int position) {

        AreaSelBean selData = areaList.get(position);
        new BaseTask<List<CityDistrict>>(this,RetroFactory.getJsonService().getCountyDistrict(selData.getCode())).handleResponse(new BaseTask.ResponseListener<List<CityDistrict>>(){

            @Override
            public void onSuccess(List<CityDistrict> cityDistricts) {
                villageList = new ArrayList<>();
                Integer selP = 0;
                for (int i = 0; i < cityDistricts.size(); i++) {
                    CityDistrict item = cityDistricts.get(i);
                    AreaSelBean sel = new AreaSelBean();
                    sel.setCityCode(item.getCityCode());
                    sel.setCityName(item.getCityName());
                    sel.setCityDistrict(item.getCityDistrict());

                    sel.setCountyCode(item.getCountyCode());
                    sel.setCountyName(item.getCountyName());
                    sel.setCountyDistrict(item.getCountyDistrict());

                    sel.setCode(item.getCode());
                    sel.setName(item.getZoneName());

                    if (infodata != null && infodata.getZoneCode().equals(sel.getCode())) {
                        selP = i;
                    }

                    villageList.add(sel);
                }

                Integer finalSelP = selP;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        Spinner spinner = findViewById(R.id.temp_village);
                        AreaSelAdapter adapter = new AreaSelAdapter(SetCabinetActivity.this, android.R.layout.simple_spinner_item, villageList);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinner.setAdapter(adapter);

                        spinner.setSelection(finalSelP);

                        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                villageSel = position;
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {
                                // 当未选择任何项时触发的操作
                            }
                        });

                    }
                });
            }

            @Override
            public void onFail() {

            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        //mapView.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //mapView.onDestroy();
    }

    public void hideLoadding(ProgressBar progressBar) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressBar.setVisibility(View.GONE);
            }
        });
    }
    private BucketType bucketBeanInfo;
    /**
     * 回收桶登记提交
     */
    public void  bucketSub(String name,Cabinet cabinet,int type){
        Log.e("TTT","品类名称1:  "+name);
        Map<String, String> par = new HashMap<>();
         BucketType bucketBean = new BucketType();

        par.put("name", name);
        bucketBean.setName(par.get("name"));

        String onlineStatus = "00";

        par.put("onlineStatus", onlineStatus);
        bucketBean.setStatus(onlineStatus);


        par.put("cabinetName", cabinet.getName());
        par.put("cabinetCode", cabinet.getCode());
        par.put("deviceSerialNum", DeviceKernel.deviceSerialNum);
        bucketBean.setCabinetCode(cabinet.getCode());
        bucketBean.setCabinetName(cabinet.getName());

        String compressStatus = "00";

        par.put("compressStatus", compressStatus);
        bucketBean.setCompressStatus(compressStatus);

        if(name.equals("纸类")||name.equals("全品类")) {
            par.put("capacity", "30");
            bucketBean.setCapacity("30");
        }else if(name.equals("塑料类")){
            par.put("capacity", "10");
            bucketBean.setCapacity("10");
        }else{
            par.put("capacity", "20");
            bucketBean.setCapacity("20");

        }

        par.put("usedCapacity", "0");
        bucketBean.setUsedCapacity("0");
        List<Catalogs> list = deviceKernel.getRuntime().getCatalogs();

            for (Catalogs catalog : list) {
                Log.e("TTT","品类名称2:  "+catalog.getName());
                if (catalog.getName() != null && catalog.getName().equals(name)) {
                    par.put("recycleCataCode", catalog.getCode());
                    par.put("recycleCataName", catalog.getName());
                    bucketBean.setRecycleCataCode(catalog.getCode());
                    bucketBean.setRecycleCataName(catalog.getName());
                    Log.e("TTT","品类名称3:  "+catalog.getName());
                    break;
                }
            }


        HardwareCategory itype =  hardType.get(1);
        par.put("hardwareName", itype.getName());
        par.put("hardwareLevel", itype.getLevel());
        par.put("hardwareCode", itype.getCode());
        bucketBean.setHardwareCode(itype.getCode());
        bucketBean.setHardwareName(itype.getName());
        bucketBean.setHardwareLevel(itype.getLevel());


        setBucketAdd(par,name,type,cabinet);
    }
    /**
     * 添加注册桶
     */
    private void setBucketAdd(Map<String, String> par,String name,int type,Cabinet cabinet) {
        String bucketStr = (String) SharedPreferencesUtils.getParam(this, "bucket", "");
        if (!bucketStr.equals("")) {
            Type dev = new TypeToken<List<BucketType>>() {
            }.getType();
            List<BucketType> bucketTypes = gson.fromJson(bucketStr, dev);
            for(BucketType bucketType :bucketTypes){
                if(bucketType.getName().equals(name)){
                    bucketBeanInfo = bucketType;
                }
            }
        }
        if(bucketBeanInfo==null){
            new BaseTask<String>(this,RetroFactory.getJsonService().addBucket(RetroFactory.getJSON2(par))).handleResponse(new BaseTask.ResponseListener<String>() {
                @Override
                public void onSuccess(String o) {
//                    progressBar.setVisibility(View.GONE);
                    updata(par,o,type,cabinet);
                }

                @Override
                public void onFail() {
//                    progressBar.setVisibility(View.GONE);
                }
            });
        }else{
            par.put("code", bucketBeanInfo.getCode());

            new BaseTask<>(this,RetroFactory.getJsonService().updataBucket(RetroFactory.getJSON2(par))).handleResponse(new BaseTask.ResponseListener() {
                @Override
                public void onSuccess(Object o) {
//                    progressBar.setVisibility(View.GONE);
                    updata(par,bucketBeanInfo.getCode(),type,cabinet);
                }

                @Override
                public void onFail() {
//                    progressBar.setVisibility(View.GONE);
                }
            });
        }
    }
    private void updata(Map<String, String> par,String code,int type,Cabinet cabinet){

            BucketType   bucketBeanInfo = new BucketType();

        bucketBeanInfo.setStatus(par.get("onlineStatus"));
        bucketBeanInfo.setCompressStatus(par.get("compressStatus"));
        bucketBeanInfo.setHardwareName(par.get("hardwareName"));
        bucketBeanInfo.setCapacity(par.get("capacity"));
        bucketBeanInfo.setHardwareLevel(par.get("hardwareLevel"));
        bucketBeanInfo.setHardwareCode(par.get("hardwareCode"));
        bucketBeanInfo.setName(par.get("name"));
        bucketBeanInfo.setRecycleCataName(par.get("recycleCataName"));
        bucketBeanInfo.setUsedCapacity(par.get("usedCapacity"));
        bucketBeanInfo.setRecycleCataCode(par.get("recycleCataCode"));
        bucketBeanInfo.setCabinetName(par.get("cabinetName"));
        bucketBeanInfo.setCabinetCode(par.get("cabinetCode"));
        if(code!=null)
            bucketBeanInfo.setCode(code);

        if(Constant.screenWidth ==800){
            bucketBeanInfo.setNum(1);
        }else{
            if(par!=null&&par.get("name")!=null) {
                if (par.get("name").contains("纸")) {
                    bucketBeanInfo.setNum(1);
                } else if (par.get("name").contains("金属")) {
                    bucketBeanInfo.setNum(2);
                } else if (par.get("name").contains("塑料")) {
                    bucketBeanInfo.setNum(3);
                } else if (par.get("name").contains("全品")) {
                    bucketBeanInfo.setNum(4);
                }
            }
        }

        bucketTypes.add(bucketBeanInfo);
        if(type==1){
            bucketSub("金属类",cabinet,2);
        }else if(type ==2){
            bucketSub("塑料类",cabinet,3);

        }else if(type ==3){
            bucketSub("全品类",cabinet,4);
        }else if(type ==4||type ==0) {
            SharedPreferencesUtils.setParam(SetCabinetActivity.this, "bucket", gson.toJson(bucketTypes));
        }
    }
    private void sendHeat(){
        String cabinetStr = (String) SharedPreferencesUtils.getParam(this, "cabinet", "");
        if(!cabinetStr.equals("")) {
            Type cType = new TypeToken<Cabinet>() {
            }.getType();
            Cabinet cabinet = gson.fromJson(cabinetStr, cType);
            Map<String, Object> par = new HashMap<>();
            par.put("cabinetCode",cabinet.getCode() );
            par.put("name", cabinet.getName());
            par.put("status", "00");
            par.put("tradStatus", cabinet.getTradStatus());
            List<HeatBucket> heatBuckets = new ArrayList<>();
            String bucketStr = (String) SharedPreferencesUtils.getParam(this, "bucket", "");
            if (!bucketStr.equals("")) {
                Type dev = new TypeToken<List<BucketType>>() {
                }.getType();
                List<BucketType> bucketTypes = gson.fromJson(bucketStr, dev);
                for (int i =0;i<bucketTypes.size();i++) {
                    BucketType b = bucketTypes.get(i);
                    HeatBucket heatBucket = new HeatBucket();
                    heatBucket.setCode(b.getCode());
                    heatBucket.setStatus("00");
                    heatBucket.setHardwareCode(b.getHardwareCode());
                    heatBucket.setUsedCapacity(String.valueOf(b.getWeight()));

                    heatBucket.setOverFlowStatus(b.getOverFlowStatus());
                    heatBuckets.add(heatBucket);
                }
            }
            Log.e("SSS",gson.toJson(heatBuckets));
            par.put("infos",heatBuckets);
            new BaseTask(this, RetroFactory.getJsonService().sendHeartbeat(RetroFactory.getJSON(par))).handleResponse(new BaseTask.ResponseListener() {


                @Override
                public void onSuccess(Object o) {

                }

                @Override
                public void onFail() {

                }
            });

        }
        SetCabinetActivity.this.finish();
    }
    private static String TAG = "hookWebView";
    @SuppressLint("SoonBlockedPrivateApi")
    public static void hookWebView(){
        int sdkInt = Build.VERSION.SDK_INT;
        try {
            Class<?> factoryClass = Class.forName("android.webkit.WebViewFactory");
            Field field = factoryClass.getDeclaredField("sProviderInstance");
            field.setAccessible(true);
            Object sProviderInstance = field.get(null);
            if (sProviderInstance != null) {
                Log.i(TAG,"sProviderInstance isn't null");
                return;
            }

            Method getProviderClassMethod;
            if (sdkInt > 22) {
                getProviderClassMethod = factoryClass.getDeclaredMethod("getProviderClass");
            } else if (sdkInt == 22) {
                getProviderClassMethod = factoryClass.getDeclaredMethod("getFactoryClass");
            } else {
                Log.i(TAG,"Don't need to Hook WebView");
                return;
            }
            getProviderClassMethod.setAccessible(true);
            Class<?> factoryProviderClass = (Class<?>) getProviderClassMethod.invoke(factoryClass);
            Class<?> delegateClass = Class.forName("android.webkit.WebViewDelegate");
            Constructor<?> delegateConstructor = delegateClass.getDeclaredConstructor();
            delegateConstructor.setAccessible(true);
            if(sdkInt < 26){//低于Android O版本
                Constructor<?> providerConstructor = factoryProviderClass.getConstructor(delegateClass);
                if (providerConstructor != null) {
                    providerConstructor.setAccessible(true);
                    sProviderInstance = providerConstructor.newInstance(delegateConstructor.newInstance());
                }
            } else {
                 Field chromiumMethodName = factoryClass.getDeclaredField("CHROMIUM_WEBVIEW_FACTORY_METHOD");
                chromiumMethodName.setAccessible(true);
                String chromiumMethodNameStr = (String)chromiumMethodName.get(null);
                if (chromiumMethodNameStr == null) {
                    chromiumMethodNameStr = "create";
                }
                Method staticFactory = factoryProviderClass.getMethod(chromiumMethodNameStr, delegateClass);
                if (staticFactory!=null){
                    sProviderInstance = staticFactory.invoke(null, delegateConstructor.newInstance());
                }
            }

            if (sProviderInstance != null){
                field.set("sProviderInstance", sProviderInstance);
                Log.i(TAG,"Hook success!");
            } else {
                Log.i(TAG,"Hook failed!");
            }
        } catch (Throwable e) {
            Log.w(TAG,e);
        }
    }
}
